import React, {Component, PropTypes} from 'react';

import { message, Button, Icon, Modal,Input,Radio,Alert } from 'antd';
const RadioGroup = Radio.Group;

import Question from '../view/ViewQuestion';

/**
 * 从一列数组中随机获取几个数字
 * @param arr
 * @param count
 */
function getRandNumbers(arr, count) {
  var shuffled = arr.slice(0), i = arr.length, min = i - parseInt(count), temp, index;
  while (i-- > min) {
    index = Math.floor((i + 1) * Math.random());
    temp = shuffled[index];
    shuffled[index] = shuffled[i];
    shuffled[i] = temp;
  }
  return shuffled.slice(min);
}

let tfng_num = 0,single_num = 0,multiple_num = 0,tfng_score = 0,single_score =0,multiple_score = 0;

export default class Step2 extends Component {

  state = {
    questionModal : false,
    exam_tfng : {
      score : '',
      num : ''
    },
    exam_single : {
      score : '',
      num : ''
    },
    exam_multiple : {
      score : '',
      num : ''
    },
    exam_total : '',
    exam_qetype : '0'
  }

  constructor (props) {
    super(props);
    this.q_id = null;
  }

  componentDidMount () {
    console.log(this.q_id);
    const {exam} = this.props;
    const examdetail = exam.get('examdetail').toJS();
    if(examdetail.exam_tfng && examdetail.exam_single && examdetail.exam_multiple){
      tfng_score = parseInt(examdetail.exam_tfng.score);
      single_score = parseInt(examdetail.exam_single.score);
      multiple_score = parseInt(examdetail.exam_multiple.score);
    }
    examdetail.exam_questions && this.computeTotalScore(examdetail.exam_questions);
    if(examdetail.exam_qetype){
      this.setState({
        exam_qetype : examdetail.exam_qetype
      })
    }
  }

  /**
   * 点击上传文件
   */
  handleFileClick () {
    this.q_id = null;
    this.refs.myFile.click();
  }

  /**
   * 点击重新上传文件
   */
  handleNewFileClick (q_id) {
    this.q_id = q_id;
    this.refs.myFile.click();
  }

  notice (text) {
    Modal.error({
      title: '错误提示',
      content: text,
    });
  }

  /**
   * 文件上传
   */
  handleFileChange () {
    console.log(this.q_id);
    const {examActions, $loki} = this.props;
    var filePath = this.refs.myFile.value;
    if(!filePath) return ;

    if(this.q_id){
      examActions.postQuestionReUpload({
        $loki,
        filePath,
        id : this.q_id
      }).then(data=>{
        this.refs.myFile.value = '';
        message.success('试题导入成功');
      }).catch(err=>{
        message.error(err);
      });
    }else{
      examActions.postQuestionUpload({
        $loki,
        filePath
      }).then(data=>{
        this.refs.myFile.value = '';
        message.success('试题导入成功');
      }).catch(err=>{
        message.error(err);
      });
    }
  }

  /**
   * 计算总分,同时更新值
   */
  computeTotalScore(questions){

    if(questions){
      tfng_num = 0; single_num =0; multiple_num = 0;
      questions.forEach(item=>{
        if(item.tfng) tfng_num += parseInt(item.tfng);
        if(item.single) single_num += parseInt(item.single);
        if(item.multiple) multiple_num += parseInt(item.multiple);
      });
    }
    let exam_total = tfng_num * tfng_score + single_num*single_score + multiple_num*multiple_score;
    this.setState({
      exam_tfng : {
        score : tfng_score,
        num : tfng_num
      },
      exam_single : {
        score : single_score,
        num : single_num
      },
      exam_multiple : {
        score : multiple_score,
        num : multiple_num
      },
      exam_total
    })
  }

  /**
   * 修改数字
   */
  handleNumChange (e,type,id) {

    const {examActions, $loki} = this.props;
    const num = e.target.value;
    if(!num) return false;
    examActions.changeQuestionNumber({
      id,
      type,
      num,
      $loki
    }).then(data=>{
      this.computeTotalScore(data.info);
    });
  }

  /**
   * 修改分数
   */
  handleScoreChange(e,type){
    let val = parseInt(e.target.value);
    if(type == 'tfng'){
      tfng_score = val;
    }else if(type == 'single'){
      single_score = val;
    }else if(type == 'multiple'){
      multiple_score = val;
    }
    this.computeTotalScore();
  }

  /**
   * 修改考题类型
   */
  handleTypeChange(e){
    let val = e.target.value;
    this.setState({
      exam_qetype : val
    })
  }

  /**
   * 删除一份试题
   * @param id
   */
  handleQuestionDelete(id) {
    const {examActions, $loki} = this.props;
    examActions.deleteQuestion({
      id,
      $loki
    })
  }

  /**
   * 查看试题
   * @param q_id
   */
  handleViewQuestions(q_id){
    const {examActions, $loki} = this.props;
    this.q_id = q_id;
    const exam_question_path = 'dba/questions/question_'+$loki+'.json';
    examActions.getQuestionList({
      path : exam_question_path,
      course_id : q_id
    }).then(data=>{
      this.setState({questionModal:true})
    })
  }

  /**
   * 下一步试题表单提交
   * @param formdata
   */
  handleFormOk () {
    const {examActions, exam} = this.props;
    const examdetail = exam && exam.get('examdetail').toJS();
    const list = exam.get('questionItems') && exam.get('questionItems').toArray();
    const questionItems = list || examdetail.exam_questions || [];
    let {exam_tfng,exam_single,exam_multiple,exam_qetype,exam_total} = this.state;

    if(!questionItems || questionItems.length < 1){
      message.error('请导入题库');
      return false;
    };

    let exam_tfng_array = [], exam_single_array = [], exam_multiple_array = [];
    if(this.state.exam_qetype === "0"){
      questionItems.forEach((qitems)=>{
        exam_tfng_array = exam_tfng_array.concat(getRandNumbers(qitems.tfng_list,qitems.tfng));
        exam_single_array = exam_single_array.concat(getRandNumbers(qitems.single_list,qitems.single));
        exam_multiple_array = exam_multiple_array.concat(getRandNumbers(qitems.multiple_list,qitems.multiple));
      });
    }

    exam_tfng['total'] = parseInt(exam_tfng.score)*parseInt(exam_tfng.num);
    exam_single['total'] = parseInt(exam_single.score)*parseInt(exam_single.num);
    exam_multiple['total'] = parseInt(exam_multiple.score)*parseInt(exam_multiple.num);

    const formdata = {
      $loki : this.props.$loki,
      exam_question_path : 'dba/questions/question_'+this.props.$loki+'.json',
      exam_qetype,
      exam_tfng,
      exam_single,
      exam_multiple,
      exam_tfng_array,
      exam_single_array,
      exam_multiple_array
    };

    examActions.postEditExam(formdata).then(data=>{
      this.props.next();
    }).catch(err=>{
      message.error(err);
    });

  }

  render() {

    const {exam} = this.props;
    const questionItems = exam.get('questionItems') && exam.get('questionItems').toArray();
    const examdetail = exam.get('examdetail').toJS();
    const list = questionItems || examdetail.exam_questions || [];
    const pagination = {
      total : list ? list.length : 0,
      pageSize : 20
    }

    return (
      <div className="ant-steps-wraper">
        <div className="steps-content">
          <Alert message="温馨提示:总的试题数量无法编辑,会自动计算导入的单门试题设置的试题数量." type="success" />
          <ul className="steps-score-wrap">
            <li>
              <span className="steps-score-wrap-title">试题类型:</span>
              <RadioGroup value={this.state.exam_qetype} onChange={(e)=>{this.handleTypeChange(e)}}>
                <Radio value="0">题目相同</Radio>
                <Radio value="1">题目不同</Radio>
              </RadioGroup>
            </li>
            <li>
              <span className="steps-score-wrap-title">试题分值:</span>
              <span className="steps-score-item" style={{'marginLeft':'0px'}}>
                <span>判断题:</span>
                <Input placeholder="数量" type="number" value={this.state.exam_tfng.num} disabled={true} className="ant-course-number ant-qe-number" /> *
                <Input placeholder="分数" type="number" value={this.state.exam_tfng.score} onChange={(event)=>{this.handleScoreChange(event,'tfng')}}  className="ant-course-number" />
              </span>
              +
              <span className="steps-score-item">
                <span>单选题:</span>
                <Input placeholder="数量" type="number" value={this.state.exam_single.num} disabled={true} className="ant-course-number ant-qe-number" /> *
                <Input placeholder="分数" type="number" value={this.state.exam_single.score} onChange={(event)=>{this.handleScoreChange(event,'single')}}  className="ant-course-number" />
              </span>
              +
              <span className="steps-score-item">
                <span>多选题:</span>
                <Input placeholder="数量" type="number" value={this.state.exam_multiple.num} disabled={true} className="ant-course-number ant-qe-number" /> *
                <Input placeholder="分数" type="number" value={this.state.exam_multiple.score} onChange={(event)=>{this.handleScoreChange(event,'multiple')}} className="ant-course-number" />
              </span>
              =
              <span className="steps-score-total">
                {this.state.exam_total}分
              </span>
            </li>
          </ul>

          <input type="file" style={{display:'none'}} ref="myFile" accept=".xlsx" onChange={this.handleFileChange.bind(this)} />
          <ul className="ant-course-list">

            {

              list.map((item)=>{
                return (
                  <li key={item.id}>
                    <span>课程名:</span>
                    <Input value={item.name} disabled={true} className="ant-course-title" />
                    <span className="ml">判断题:</span><Input placeholder="数量" type="number" defaultValue={item.tfng} className="ant-course-number" onChange={(event)=>{ this.handleNumChange(event,'tfng',item.id) }} />
                    <span className="ml">单选题:</span><Input placeholder="数量" type="number" defaultValue={item.single} className="ant-course-number" onChange={(event)=>{ this.handleNumChange(event,'single',item.id) }} />
                    <span className="ml">多选题:</span><Input placeholder="数量" type="number" defaultValue={item.multiple} className="ant-course-number" onChange={(event)=>{ this.handleNumChange(event,'multiple',item.id) }} />
                    <span style={{marginLeft:'20px'}}>
                      <a href="javascript:;" className="ml mr" onClick={this.handleViewQuestions.bind(this,item.id)}>查看</a>/
                      <a href="javascript:;" className="ml mr" onClick={this.handleNewFileClick.bind(this,item.id)}>重新导入</a>/
                      <a href="javascript:;" className="ml" onClick={this.handleQuestionDelete.bind(this,item.id)}>删除</a>
                    </span>
                  </li>
                )
              })
            }

            <li className="ant-import" onClick={this.handleFileClick.bind(this)}>
              <Icon type="plus" /><span>点击这里,导入试题</span>
            </li>
          </ul>

        </div>

        <div className="steps-action">
          <Button type="primary" className="ant-next-btn" onClick={() => {
            if(this.state.exam_total != 100){
              Modal.confirm({
                title: '信息提示',
                content: '本次考试总分不是100分,是否继续',
                okText: '继续',
                cancelText: '取消',
                onOk : ()=>{
                  this.handleFormOk();
                }
              });
            }else{
              this.handleFormOk()
            }
          }}>下一步</Button>
          <Button className="ant-previous-btn" onClick={() => this.props.prev()}>
            返回上一步
          </Button>
        </div>

        <Modal title="试题列表" visible={this.state.questionModal} footer={null} onCancel={()=>{ this.setState({questionModal:false})}} width={900}>
          <Question $loki={this.props.$loki} course_id={this.q_id} {...this.props}/>
        </Modal>

      </div>
    )
  }

}

